/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool GetPath(TreeNode* root,TreeNode* p,stack<TreeNode*>& path)
    {
        if(root==nullptr) return false;
        path.push(root);

        if(root==p){
            return true;
        }
        if(GetPath(root->left,p,path)){
            return true;
        }
        if(GetPath(root->right,p,path)){
            return true;
        }

        path.pop();
        return false;
    }
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        stack<TreeNode*> Ppath,Qpath;
        GetPath(root,p,Ppath);
        GetPath(root,q,Qpath);
        
        while(Ppath.size()!=Qpath.size())
        {
            if(Ppath.size()>Qpath.size()){
                Ppath.pop();
            }else{
                Qpath.pop();
            }
        }
        while(Ppath.top()!=Qpath.top()){
            Ppath.pop();
            Qpath.pop();
        }
        return Ppath.top();
    }
};